﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xinkui.Entity.AutoGenerator;

namespace Xinkui.WebModel.Cache.View {
    public class CategoryView {

        public static CategoryView GetInstance(CategoryView parent, CommonCategory_Entity entity, Func<int, List<CommonCategory_Entity>> getData) {
            CategoryView view = new CategoryView() { PathIds = entity.DirPath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries).ToList(), CategoryInfo = entity };
            if (parent != null) {
                view.DirPathName = string.Format("{0}/{1}", parent.DirPathName, entity.Title);
                view.Parent = parent;
            }
            else {
                view.DirPathName = entity.Title;
            }
            var subCategorys = getData(entity.CategoryID);
            if (subCategorys != null && subCategorys.Count > 0) {
                view.SubViews = new List<CategoryView>(subCategorys.Count);
                foreach (var subItem in subCategorys) {
                    view.SubViews.Add(CategoryView.GetInstance(view, subItem, getData));
                }
            }
            else {
                view.SubViews = new List<CategoryView>(0);
                view._totalProduct = entity.ProductCount;
            }

            return view;
        }

        public string DirPathName { get; set; }

        public CommonCategory_Entity CategoryInfo { get; set; }

        public CategoryView Parent { get; set; }

        public List<string> PathIds { get; set; }

        private int _totalProduct = 0;
        public int TotalProduct {
            get {
                if (SubViews != null) {
                    return _totalProduct + SubViews.Sum(u => u.TotalProduct);
                }
                else {
                    return _totalProduct;
                }
            }
        }

        public List<CategoryView> SubViews { get; set; }
    }
}
